import {
  inventoryPageApi,
  addInventoryApi,
  editInventoryApi,
  delInventoryApi
} from '@/api/workflow/inventory'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { InventoryModel } from '@/api/model/inventory-model'
import { userInfo } from '~/types/user'
import { userInfoModel } from '@/api/model/userModel'
import dayjs from 'dayjs'

type Props = {
  handleType: Ref<'add' | 'edit' | 'check'>
  handleTag: Ref<string>
  inventoryModalShow: Ref<boolean>
  inventoryForm: Ref<Partial<InventoryModel>>
  proTableInst: Ref<ProTableInst | null>
  userInfo: Ref<userInfo<userInfoModel>>
  memberOptions: Ref<Array<any>>
}

export const useInventoryApi = ({
  handleType,
  handleTag,
  inventoryModalShow,
  inventoryForm,
  proTableInst,
  userInfo,
  memberOptions
}: Props) => {
  const confirmLoading = ref(false)

  // 获取盘点列表
  const fetchInventoryPage = async (
    pageRequest: PageRequest,
    queryParams: InventoryModel
  ) => {
    const res = await inventoryPageApi({
      ...queryParams,
      orgId: userInfo.value.orgId,
      pageRequest
    })

    if (res.code === '0000') {
      return {
        data: res.data?.content,
        total: res.data?.total
      }
    }
  }

  // 新增or修改盘点
  const fetchAddOrEditInventory = async () => {
    try {
      confirmLoading.value = true
      const fetch =
        handleType.value === 'add' ? addInventoryApi : editInventoryApi
      const data =
        handleType.value === 'add'
          ? {
              ...inventoryForm.value,
              receivePerson: userInfo.value.userName,
              receivePersonId: userInfo.value.userId,
              receiveBranch: userInfo.value.orgName,
              receiveBranchId: userInfo.value.orgId,
              inventoryPerson: useDictDisplay(
                memberOptions.value,
                inventoryForm.value.inventoryPersonId
              ),
              receiveDate: dayjs().format('YYYY-MM-DD')
            }
          : {
              ...inventoryForm.value,
              inventoryPerson: useDictDisplay(
                memberOptions.value,
                inventoryForm.value.inventoryPersonId
              )
            }
      if (data.__displayValue__) delete data.__displayValue__
      const res = await fetch(data)
      if (res.code === '0000') {
        useMsg('success', handleTag.value + '成功')
        proTableInst.value?.reload()
        inventoryModalShow.value = false
      }
    } catch (e) {
      console.log(e)
    } finally {
      confirmLoading.value = false
    }
  }

  // 删除盘点
  const fetchDelInventory = async (id) => {
    try {
      const res = await delInventoryApi({ id })
      if (res.code === '0000') {
        useMsg('success', '删除成功')
        proTableInst.value?.reload()
      }
    } catch (e) {
      console.log(e)
    }
  }

  return {
    fetchInventoryPage,
    fetchAddOrEditInventory,
    fetchDelInventory,
    confirmLoading
  }
}
